package com.msh.frame.common.util;


import com.msh.frame.client.exception.BizException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.Random;
import lombok.extern.slf4j.Slf4j;

/**
 * Decoder Encoder 是线程安全的
 */
@Slf4j
public class Base64Util {

  public static Decoder base64Decoder = Base64.getDecoder();
  public static Encoder base64Encoder = Base64.getEncoder();


  //线程安全测试方法
  public static void main(String[] args) throws InterruptedException {
    Decoder decoder = Base64.getDecoder();
    MultiThreadTestUtil.threadTest(null, e -> {
      String str = String.valueOf(new Random().nextDouble());
      String s4 = Base64Util.encrypt(str);
      String s5 = new String(Base64Util.decrypt(s4));
      if (!str.equals(s5)) {
        System.out.println(str.equals(s5));
      }
    });
  }


  public static Base64Instance getInstance() {
    return new Base64Instance();
  }

  /**
   * 加密
   */
  public static String encrypt(String src) throws UnsupportedEncodingException {
    return encryptBuffer(src.getBytes("UTF-8"));
  }

  /**
   * 加密
   */
  public static String encryptBuffer(byte[] bytes) {
    return base64Encoder.encodeToString(bytes);
  }

  /**
   * 解密
   */
  public static String decrypt(String src) throws IOException {
    return new String(decodeBuffer(src), "UTF-8");
  }

  /**
   * 解密
   */
  public static byte[] decodeBuffer(String str) {
    return base64Decoder.decode(str);
  }

  public static class Base64Instance {

    public String encrypt(String src) {
      try {
        return Base64Util.encrypt(src);
      } catch (Exception e) {
        log.error("加密失败", e);
        throw new BizException("Base64加密失败");
      }
    }

    public String decrypt(String src) {
      try {
        return Base64Util.decrypt(src);
      } catch (Exception e) {
        log.error("解密失败", e);
        throw new BizException("Base64解密失败");
      }
    }
  }

}
